🧠 Java Memory Management

πŸ“‹ What is Memory Management in Java?

When you run a Java program, Java needs memory to:

πŸ‘‰ Key Point: Java automatically manages memory using the JVM (Java Virtual Machine) and Garbage Collector (like a cleaner).

🏠 Real-Life Example

Imagine your computer is a house:

JVM Memory Management
  • Heap = Big cupboard shared by everyone β€” stores all objects
  • Stack = Small desk each person (thread) uses β€” stores local variables and method info
  • Method Area = Library β€” stores blueprints (class info, static data)
  • PC Register = Pointer showing what you're currently doing
  • Native Stack = A side tool area if you call C/C++ functions

πŸ“¦ Java Memory Areas (Explained Simply)

Java Memory Areas

1. Heap Memory (Main Storage)

  • Stores:
    • All objects created using new keyword
    • Instance variables
    • Runtime constant pool (part of Method Area)
    • String Pool (special memory area inside Heap)
  • Shared by: All threads
  • Cleaned by: Garbage Collector (GC)
  • Divided into:
    • Young Generation: Newly created objects (Eden + Survivor spaces)
    • Old Generation: Long-lived objects
    • Metaspace (Java 8+): Class metadata, method info
πŸ”§ Example 1:
String name = new String("Deepak");

πŸ‘‰ Result: One "Deepak" in String Pool + another new object in Heap.

πŸ”§ Example 2 (String Pool):
String s1 = "Hello";  
String s2 = "Hello";

πŸ‘‰ Result: Both s1 and s2 point to the same object in String Pool, no duplicate created.

πŸ”§ Example 3 (intern() method):
String s1 = new String("World");  
String s2 = s1.intern();  
String s3 = "World";

πŸ‘‰ Result: s2 and s3 refer to the same object in String Pool, but s1 is a separate object in Heap.

πŸ“Œ Important Notes on Heap & String Pool:

  • Heap is the biggest memory area in JVM, used for almost all object storage.
  • Memory management in Heap is automatic (handled by Garbage Collector).
  • String Pool optimizes memory by reusing immutable String objects.
  • Too many Strings without pooling can cause OutOfMemoryError.

πŸ”‘ About intern()

  • intern() is a method of String class.
  • It checks whether the String already exists in the String Pool.
  • If it exists β†’ returns reference from the pool.
  • If it doesn’t exist β†’ adds the String to the pool and returns that reference.
String x = new String("Java");
String y = x.intern();
String z = "Java";

System.out.println(x == y); // false
System.out.println(y == z); // true
            

πŸ‘‰ Why use intern()?

  • Helps save memory by avoiding duplicate String objects.
  • Improves performance when many identical Strings are used (e.g., large text processing, XML/JSON parsing).
  • But: Excessive interning may increase GC pressure (trade-off).

2. Stack Memory (Per Thread)

  • Stores: Local variables, method calls
  • Each thread gets: Its own stack
  • Cleared when: Method ends
πŸ”§ Example:
int a = 10;

πŸ‘‰ Result: 'a' is a local variable, stored in Stack

3. Method Area / MetaSpace (Blueprints)

  • Stores: Class definitions, static variables, method names
  • Loaded: Once per class
πŸ”§ Example:
static int collegeCode = 123;

πŸ‘‰ Result: 'collegeCode' is stored in the Method Area

4. PC Register

  • Keeps track of which line in the method is being executed
  • Each thread has one

5. Native Method Stack

  • Only used when you call native (C/C++) code from Java using JNI

πŸ‘¨β€πŸ’» Full Example Code + Memory Map

public class Student {
    int age = 20;                 // Stored in Heap
    static String school = "ABC"; // Stored in Method Area

    public static void main(String[] args) {
        int roll = 101;            // Stored in Stack
        Student s1 = new Student(); // Object in Heap, ref in Stack
    }
}

🧠 Memory Map:

Memory Area What It Stores
Heap Object s1, instance variable age
Stack roll, reference to s1
Method Area Class info, school

🧹 What is Garbage Collection?

  • It automatically removes unused objects from the Heap to free memory
  • No need to use free() like in C/C++
πŸ”§ Example:
Student s1 = new Student();
s1 = null; // Now the object is not used β†’ eligible for GC

You can suggest GC like this:

System.gc(); // Suggests garbage collection (not guaranteed)

βœ… Simple Interview Questions and Answers

❓ Question βœ… Simple Answer
What is memory management? Java automatically allocates and frees memory using JVM.
What is the Heap? Stores objects. Shared by all. Cleaned by garbage collector.
What is Stack memory? Stores method calls and local variables. One per thread.
What is garbage collection? JVM removes unused objects from memory automatically.
Where are static variables stored? In the Method Area.
What is stored in Stack vs Heap? Stack = local vars, refs. Heap = objects.
Can you force GC in Java? You can suggest it using System.gc(), but it's not guaranteed.

πŸ“ Final Summary

Part Description Example
Heap Stores objects new Student()
Stack Stores method calls and variables int a = 5;
Method Area Stores class data, static vars static int x;
Garbage Collection Removes unused objects obj = null;

🎯 Key Points for Interview

  • Java uses automatic memory management (no manual free())
  • JVM memory has Heap, Stack, and Method Area
  • Objects β†’ Heap, Variables β†’ Stack, Class Info β†’ Method Area
  • Garbage Collector frees memory automatically